package com.bqy.myokgo.base.manager;

import android.app.Activity;

import com.bqy.myokgo.base.manager.event.HttpEvent;
import com.bqy.myokgo.base.manager.event.HttpEventNO;
import com.bqy.myokgo.base.manager.event.HttpEventOK;
import com.bqy.myokgo.base.okgo.bean.GuestBean;
import com.bqy.myokgo.base.okgo.bean.XXResponse;
import com.bqy.myokgo.utils.ListUtils;
import com.bqy.myokgo.utils.OnAppListener;
import com.lzy.okgo.OkGo;

import java.util.ArrayList;
import java.util.List;

/**
 * 熊猫先生
 * 关联并发的时候用
 * 2019/3/8:10:56
 */

public class HttpManager {
    public static List<String> stringList;
    public static HttpManager manager;
//    public Activity activity;

    public OnAppListener.OnHttpListener l;

    public void addListener(Activity context) {
        if (context instanceof OnAppListener.OnHttpListener) {
            l = (OnAppListener.OnHttpListener) context;
        }
    }

    public OnAppListener.OnHttpListener getListener() {
        return l;
    }

    public static HttpManager getInstance() {
        if (manager == null) {
            manager = new HttpManager();
        }
        return manager;
    }

    /**
     * 新添加
     */
    public void addHttpFlag(String s) {
        if (stringList == null) {
            stringList = new ArrayList<>();
        }
        if (!stringList.contains(s)) {//判断是否存在,不存在就添加
            stringList.add(s);
        }
    }

    /**
     * 单次请求成功
     */
    public static List<HttpEvent> httpEventList = new ArrayList<>();

    public void addHttpOK(String s, Object... o) {
        stringList.remove(s);
        httpEventList.add(new HttpEvent(s, o));//添加一个数据
        //加载完毕
        if (ListUtils.isEmpty(stringList)) {
            getListener().onHttpOK(new HttpEventOK(httpEventList));
            httpEventList.clear();
        }
    }

    /**
     * 加载失败 清除所有请求
     */
    public void cancelAll(com.lzy.okgo.model.Response<XXResponse<GuestBean>> responses) {
        if (ListUtils.isEmpty(stringList)) {
            return;
        }
        //关闭所有请求
        for (int i = 0; i < stringList.size(); i++) {
            OkGo.getInstance().cancelTag(stringList.get(i));
        }
        //清楚所有记录
        stringList.clear();
        httpEventList.clear();
        getListener().onHttpNO(new HttpEventNO(responses));
    }
}
